package org.example.zsfmybatis.service;

import org.example.zsfmybatis.mapper.UserMapper;
import org.example.zsfmybatis.model.Meals;
import org.example.zsfmybatis.model.Order;
import org.example.zsfmybatis.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.transform.Result;

@Service
public class UserService{
    @Autowired
    UserMapper userMapper;
    @Autowired
    MealsService mealsService;
    @Autowired
    OrderService orderService;

    public int add(User user){
        if(user!=null){
            userMapper.add(user);
            return 1;
        }else
            return 0;
    }

    public User getUser(String id){
        return userMapper.getUser(id);
    }
    public int findUser(String id){
        User user =userMapper.getUser(id);
        if(user!=null){
            return 1;
        }else{
            return 0;
        }
    }

    public void update(User user){
        userMapper.update(user);
    }
    public void delete(User user){
        userMapper.delete(user);
    }

    @Transactional
    public String order(String meals_id,String user_id,int sum){

        if(findUser(user_id)==0){
            return "用户不存在";
        }else{
            Meals meals=new Meals();
            Order order=new Order();
            if (mealsService.pricesum(meals_id,sum)>0){
                meals=mealsService.findbyid(meals_id);
                order.setUserId(Integer.parseInt(user_id));
                order.setSum(sum);
                order.setMealId(Integer.parseInt(meals_id));
                order.setPrice((float) meals.getPrice());
                orderService.addOrder(order);
                return "创建订单成功";
            }else{
                return "库存不足";
            }
        }
    }
}